import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_douban/config/app_config.dart';
import 'package:flutter_douban/config/event_bus_util.dart';
import 'package:flutter_douban/config/sqflite/note_db_provider.dart';
import 'package:flutter_douban/loading/custom_footer.dart';
import 'package:flutter_douban/loading/custom_header.dart';
import 'package:flutter_douban/main_page/collect/view/note_item_cell.dart';
import 'package:flutter_douban/model/note_model.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';

class CollectionNotePage extends StatefulWidget {
  const CollectionNotePage({Key? key}) : super(key: key);

  @override
  _CollectionNotePageState createState() => _CollectionNotePageState();
}

class _CollectionNotePageState extends State<CollectionNotePage> {
  List<NoteModel> _noteList = [];

  /// 下拉刷新控制器
  EasyRefreshController? _easyRefreshController;

  /// 独立的滚动视图 防止tab切换时触发下拉刷新
  ScrollController? _scrollController;
  StreamSubscription<CacheNoteEvent>? _cacheNoteSubscription;
  StreamSubscription<LoginEvent>? _loginSubscription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _scrollController = ScrollController();
    _loginSubscription = EventBusUtil.listen((event) {
      setState(() {
        _getData();
      });
    });
    _cacheNoteSubscription = EventBusUtil.listen((event) {
      setState(() {
        _getData();
      });
    });
    _getData();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _cacheNoteSubscription?.cancel();
    super.dispose();
  }

  Future<void> _getData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? numberId = prefs.getString(AppConfig.numberId);
    NoteDbProvider provider = new NoteDbProvider();
    List<NoteModel> list = [];
    provider.getAllNoteInfo(numberId!).then((value) => {
      list = value,
      setState(() {
        _noteList = list;
      }),
    });
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
        // 开启首次加载刷新
        firstRefresh: false,
        header: CustomHeaderView(),
        footer: CustomFooterView(),
        controller: _easyRefreshController,
        enableControlFinishRefresh: false,
        enableControlFinishLoad: true,
        onRefresh: _getData,
        child: Container(
          color: Colors.white,
          child: ListView.builder(
            controller: _scrollController,
            itemCount: _noteList.length,
            shrinkWrap: true, //增加
            itemBuilder: (BuildContext context, int index) {
              return NoteItemCell(
                model: _noteList[index],
              );
            },
          ),
        ));
  }
}
